package top.iying.lab.bytedance;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.AnchorPane;
import javafx.scene.text.Font;
import javafx.stage.Stage;

import javax.swing.*;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.net.InetAddress;

/**
 * @author 颖
 */
public class Ying extends Application {

    private long startedAt = -1;
    private int index = 0;
    private final Label ticker = new Label(String.valueOf(0));
    private final SnowflakeId snowflake = new SnowflakeId(InetAddress.getLocalHost().getHostName(), 1024);

    public Ying() throws Exception {
        new Timer(46, event ->
                Platform.runLater(() -> this.ticker.setText(
                        String.valueOf(this.getTick()))
                )
        ).start();
    }

    public static void main(String[] args) {
        Application.launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        AnchorPane anchorPane = new AnchorPane();
        anchorPane.setPrefWidth(604);
        anchorPane.setPrefHeight(604);
        // Ticker
        this.ticker.setAlignment(Pos.CENTER);
        this.ticker.setFont(Font.font(128.0));
        anchorPane.getChildren().add(this.ticker);
        AnchorPane.setTopAnchor(this.ticker, 32.0);
        AnchorPane.setLeftAnchor(this.ticker, 128.0);
        AnchorPane.setRightAnchor(this.ticker, 128.0);
        // Command
        TextField command = new TextField("/execute @a[score_tick_min=%x,score_tick=%x] ~ ~ ~ execute @e[name=%n,tag=kd] ~ ~ ~");
        command.setPrefHeight(64.0);
        anchorPane.getChildren().add(command);
        AnchorPane.setTopAnchor(command, 228.0);
        AnchorPane.setLeftAnchor(command, 64.0);
        AnchorPane.setRightAnchor(command, 64.0);
        // Commands
        TextArea commands = new TextArea();
        commands.setPrefHeight(64.0);
        commands.setEditable(false);
        anchorPane.getChildren().add(commands);
        AnchorPane.setTopAnchor(commands, 306.04);
        AnchorPane.setBottomAnchor(commands, 164.0);
        AnchorPane.setLeftAnchor(commands, 64.0);
        AnchorPane.setRightAnchor(commands, 64.0);
        // 控制按钮
        Button controlButton = new Button("开始");
        controlButton.setPrefHeight(64);
        controlButton.setOnMouseClicked(event -> {
            if (this.startedAt != -1) {
                this.startedAt = -1;
                try {
                    BufferedWriter out = new BufferedWriter(new FileWriter(String.format("%d.mcfunction", this.snowflake.nextId())));
                    out.write(commands.getText());
                    out.close();
                } catch (Exception exception) {
                    exception.printStackTrace();
                }
                controlButton.setText("开始");
            } else {
                commands.setText("");
                this.startedAt = System.currentTimeMillis();
                this.index = 0;
                controlButton.setText("结束");
            }
        });
        // 动态获取焦点
        controlButton.focusedProperty().addListener((observable, oldValue, newValue) -> {
            if (!newValue && this.startedAt != -1) {
                // 获取焦点
                controlButton.requestFocus();
            }
        });
        // 监听键盘事件
        controlButton.setOnKeyPressed(event -> {
            // 按下 空格 键
            if (event.getCode() == KeyCode.SPACE) {
                if (this.startedAt != -1) {
                    this.index++;
                    String newCommand = command.getText()
                            .replaceAll("%x", String.valueOf(this.getTick()))
                            .replaceAll("%n", String.valueOf(this.index));
                    commands.appendText(String.format("%s\n", newCommand));
                    commands.selectEnd();
                    commands.deselect();
                } else {
                    controlButton.getOnMouseClicked().handle(null);
                }
            } else if (event.getCode() == KeyCode.ENTER) {
                commands.appendText("\n");
                commands.selectEnd();
                commands.deselect();
            }
        });
        anchorPane.getChildren().add(controlButton);
        AnchorPane.setLeftAnchor(controlButton, 128.64);
        AnchorPane.setRightAnchor(controlButton, 128.64);
        AnchorPane.setBottomAnchor(controlButton, 64.0);
        // 展示界面
        Scene scene = new Scene(anchorPane);
        primaryStage.setScene(scene);
        primaryStage.show();
        // 获取焦点
        controlButton.requestFocus();
    }

    private long getTick() {
        return (System.currentTimeMillis() - this.startedAt) / 50;
    }

}
